<?php
namespace app\admin\model;


use app\api\model\UserGreenPointsLog;
use app\model\Base;

class User extends Base
{
    public function userLevel()
    {
        return $this->hasOne(Level::class, 'id', 'level_id')->bind([
            'level_name'=>'name',
        ]);
    }

    public function getLevelNameAttr($value)
    {
        return $value ?? '普通用户';
    }

    public function userVirtualLevel()
    {
        return $this->hasOne(Level::class, 'id', 'virtual_level_id')->bind([
            'virtual_level_name'=>'name',
        ]);
    }

    public function getVirtualLevelNameAttr($value)
    {
        return $value ?? '普通用户';
    }

    public function getScoreFormatAttr($value, $data)
    {
        return bcdiv_amount($data['score']);
    }

    public function getSpendingFormatAttr($value, $data)
    {
        return bcdiv_amount($data['spending']);
    }

    public function getPerformanceFormatAttr($value, $data)
    {
        return bcdiv_amount($data['performance']);
    }






//    public function getInvestBalanceFormatAttr($value, $data)
//    {
//        $str = ModeOrders::where('user_id', $data['id'])
//            ->where('status', '=', 'payed')
//            ->where('is_delete', '=', 0)
//            ->where('type', 4)->sum('remain_earnings');
//        return round((float)$str / 100, 2);
//    }

//    public function getGreenPointsFormatAttr($value, $data)
//    {
//        $str = ModeOrders::where('user_id', $data['id'])
//            ->where('status', '=', 'payed')
//            ->where('is_delete', '=', 0)
//            ->whereIn('type', [1, 2])->sum('remain_earnings');
//        return round((float)$str / 100, 2);
//    }

    public function getTransferFormatAttr($value, $data)
    {
        $str = $data['transfer_switch'] == 'on' ? '开启' : '关闭';
        return $str;
    }

    public function getReleaseFormatAttr($value, $data)
    {
        $str = $data['release_switch'] == 'on' ? '开启' : '关闭';
        return $str;
    }

//    public function getModeOneLevelAttr($value, $data)
//    {
//        if($data['mode_one_level_id'] == 0){
//            return '无等级';
//        }else{
//            return ModeOneLevel::where('id', $data['mode_one_level_id'])->value('name');
//        }
//    }
//
//    public function getModeThreeLevelAttr($value, $data)
//    {
//        if($data['mode_three_level_id'] == 0){
//            return '无等级';
//        }else{
//            return ModeThreeLevel::where('id', $data['mode_three_level_id'])->value('name');
//        }
//    }


//    public function getAllChildren($pid){
//        static $arr = [];
//        $list = self::where('pid', $pid)->column('id', 'id');
//        if($list){
////            dd($list);
//            foreach ($list as $item){
////                dd($item);
//                $arr[] = $item;
//                $this->getAllChildren($item);
//            }
//        }else{
////            $arr[] = $pid;
////            echo $pid;
//            return;
//        }
//        return $arr;
//    }

    public function getAllChildren($pid){
        $teamMembers = self::where('pid', $pid)->column('id', 'id');
        if (empty($teamMembers)) {
            return [];
        }
        $users = [];
        // 遍历团队成员，递归查询每个成员的下级用户
        foreach ($teamMembers as $member) {
            // 查询当前成员的下级用户
            $subUsers = $this->getAllChildren($member);
            // 将当前成员和其下级用户合并为一个数组
            $users = array_merge($users, [$member], $subUsers);
        }
        return $users;
    }

    public function getUserTree($pid){
        $users = [];
        $teamMembers = self::with(['userLevel'])
            ->field('id, pid, phone, spending, performance, level_id')
            ->where('pid', $pid)->select();
        if ($teamMembers) {
            // 遍历团队成员，递归查询每个成员的下级用户
            foreach ($teamMembers->toArray() as $member) {
//                $user = $member;
//                // 查询当前成员的下级用户
//                $user['children'] = $this->getUserTree($member['id']);
                $user['id'] = $member['id'];
                $user['title'] = '【ID：' . $member['id'] . '】【等级：' . $member['level_name']
                    . '】【个人业绩：' . $member['spending'] / 100
                    . '】【团队业绩：' . $member['performance'] / 100 . '】';
                $user['children'] = $this->getUserTree($member['id']);
                $users[] = $user;
            }
        }
        return $users;
    }

//    public function getChildren($pid)
//    {
//        $teamMembers = self::with(['userLevel'])
//            ->field('id, pid, phone, spending, performance, level_id')
//            ->where('pid', $pid)->select();
//    }

    public function getUserTree2($pid){
        $users = [];
        $teamMembers = self::with(['userLevel'])
            ->field('id, pid, phone, spending, performance, level_id')
            ->where('pid', $pid)->select();
        if ($teamMembers) {
            // 遍历团队成员，递归查询每个成员的下级用户
            foreach ($teamMembers->toArray() as $member) {
//                $user = $member;
//                // 查询当前成员的下级用户
//                $user['children'] = $this->getUserTree($member['id']);
                $user['id'] = $member['id'];
                $user['title'] = '【ID：' . $member['id'] . '】【等级：' . $member['level_name']
                    . '】【个人业绩：' . $member['spending'] / 100
                    . '】【团队业绩：' . $member['performance'] / 100 . '】';
                $user['children'] = $this->getUserTree($member['id']);
                $users[] = $user;
            }
        }
        return $users;
    }

    //获取团队所有需要的字段
    public function getUserTreeField($pid, $field){
        $users = [];
        $teamMembers = self::field($field)->where('pid', $pid)->select();
        if ($teamMembers) {
            // 遍历团队成员，递归查询每个成员的下级用户
            foreach ($teamMembers->toArray() as $member) {
                $user['id'] = $member['id'];
                $users[] = $user;
                $nextUsers = $this->getUserTreeField($member['id'], $field);
                $users = array_merge($users, $nextUsers);
            }
        }
        return $users;
    }

    public function getMonthPerformanceAttr($value, $data)
    {
//        echo $data['id'] . 'amount:';
        $team = $this->getAllChildren($data['id']);
        $sum = 0.00;
        if(!is_null($team)){
            foreach ($team as $item){
//            echo $item . ',';
                $sum += BenefitOrder::whereMonth('create_time')
                    ->where('user_id', $item)
                    ->where('status', 'payed')
                    ->sum('pay_amount');

            }
        }
        return $sum;
    }

    public function getLastMonthPerformanceAttr($value, $data)
    {
//        echo $data['id'] . 'amount:';
        $team = $this->getAllChildren($data['id']);
        $sum = 0.00;
        if(!is_null($team)){
            foreach ($team as $item){
//                echo $item . 'amount:';
                $sum += BenefitOrder::whereMonth('create_time','last month')
                    ->where('user_id', $item)
                    ->where('status', 'payed')
//                    ->fetchSql(true)->select();
                    ->sum('pay_amount');
            }
        }
        return $sum;
    }

    public function getLastMonthMinePerformanceAttr($value, $data)
    {
        $sum = 0.00;
        $sum = BenefitOrder::whereMonth('create_time','last month')
            ->where('user_id', $data['id'])
            ->where('status', 'payed')
//                    ->fetchSql(true)->select();
            ->sum('pay_amount');
        return $sum;
    }

    public function getLastPerformanceAttr($value, $data)
    {
//        echo $data['id'] . 'amount:';
        $currentMonth = date('Y-m'); // 当前月份，格式为YYYY-MM
        $previousMonth = date('Y-m', strtotime('-1 month', strtotime($currentMonth . '-01'))); // 上个月份，格式为YYYY-MM
        //dd($this->model->whereBetweenTime('create_time', '2017-01-01', '2017-06-30')->fetchSql()->select());
        $team = $this->getAllChildren($data['id']);
        array_push($team, $data['id']);
        $sum = 0.00;
        if(!is_null($team)){
            foreach ($team as $item){
//                echo $item . 'amount:';
                $sum += BenefitOrder::whereBetweenTime('create_time', ($previousMonth . '-15'), ($currentMonth . '-16'))
                    ->where('user_id', $item)
                    ->where('status', 'payed')
//                    ->fetchSql(true)->select();
                    ->sum('pay_amount');
            }
        }
        return $sum;
    }

    public function getBenefitLevelFormatAttr($value, $data)
    {
        $str = '无等级';
        if($data['benefit_level_id'] > 0){
            $str = BenefitLevel::where('id', $data['benefit_level_id'])->value('name');
        }
        return $str;
    }
}